package com.zbj.homemade.mybatis;

import com.zbj.homemade.mybatis.conf.Configuration;
import com.zbj.homemade.mybatis.conf.MappedStatement;
import com.zbj.homemade.mybatis.conf.SqlCommandType;

/**
 * @program: principle
 * @description:
 * @author: Yinn
 * @create: 2019-01-11 16:46
 **/
public class DefaultSqlSessionFactory implements SqlSessionFactory {

    private String xmlLocation;

    private final Configuration configuration;

    public DefaultSqlSessionFactory(Configuration configuration, String xmlLocation) throws ClassNotFoundException {
        this.configuration = configuration;
        this.xmlLocation = xmlLocation;
        init();
    }

    private void init() throws ClassNotFoundException {
        xmlParse();
        propertiesParse();
    }

    private void xmlParse() throws ClassNotFoundException {

        //不仔细写了 用sax 或者 dom4j实现即可
        //大致就是解析每一个标签及其属性 <namespace> <select id="id" resultType="" >sql</select>

        //这里存一个xml的一个select标签模拟
        String id = "queryTestList";
        String namaspace = "com.zbj.homemade.mybatis.test";
        Class<?> resultType = this.getClass().getClassLoader().loadClass("com.zbj.homemade.mybatis.test.TestModel");
        Class<?> parameterType = this.getClass().getClassLoader().loadClass("java.lang.String");
        String sql = "select id,job_title from job where id = #{id}";
        SqlCommandType sqlCommandType = SqlCommandType.SELECT;


        MappedStatement ms = new MappedStatement();
        ms.setId(id);
        ms.setParameterType(parameterType);
        ms.setResultType(resultType);
        ms.setSql(sql);
        ms.setConfiguration(configuration);
        ms.setNamespace(namaspace);
        ms.setSqlCommandType(sqlCommandType);
        configuration.putMappedStatement(namaspace + "." + id, ms);
    }

    private void propertiesParse() {

    }

    @Override
    public SqlSession openSqlSession() {
        return new DefaultSqlSession(configuration);
    }
}
